package com.juc.threadpool;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 停止线程池
 *
 * @author mobai
 * @since 2021/3/4 10:47
 */
public class StopThreadPoolTest {

    static class CustomThreadPool extends ThreadPoolExecutor {

        private volatile boolean isStopFlag = false;

        private final Lock lock = new ReentrantLock(true);

        private final Condition condition = lock.newCondition();

        public CustomThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        }

        @Override
        protected void beforeExecute(Thread t, Runnable r) {
            super.beforeExecute(t, r);
            lock.lock();
            try {
                while (isStopFlag) {
                    condition.await();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void stop() {

            lock.lock();
            try {
                this.isStopFlag = true;
            } finally {
                lock.unlock();
            }

        }

        public void resume() {
            lock.lock();
            try {
                this.isStopFlag = false;
                condition.signalAll();
            } finally {
                lock.unlock();
            }


        }
    }


    public static void main(String[] args) throws InterruptedException {
        CustomThreadPool customThreadPool = new CustomThreadPool(5, 10, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        Task task = new Task();
        for (int i = 0; i < 1000; i++) {
            customThreadPool.execute(task);
        }
        Thread.sleep(3000);
        customThreadPool.stop();
        System.out.println("主线程关闭线程池");
        Thread.sleep(3000);
        customThreadPool.resume();
        System.out.println("主线程继续线程池");
    }

    static class Task implements Runnable {


        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "正在执行任务");
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
